<template>
	<view class="page">
		<cu-custom bgColor="bg-white" :isBack="true">
			<block slot="content">选择城市</block>
		</cu-custom>
		<view>
			<view class="item" v-if="shopLocation">
				<view class="pinyin_prefix padding-left-sm padding-top-sm padding-bottom-sm text-sm text-bold">当前定位城市</view>
				<view class="grid text-center">
					<view class="regions-item" v-if="locationLoading === 'loading'">定位中...</view>
					<view class="regions-item" v-else-if="locationLoading === 'success'"
					@tap="selected(location)">{{ location.title }}</view>
					<view class="regions-item regions-item-2" v-else @tap="getLocation">定位失败，点击重试</view>
				</view>
			</view>
			<view class="item" v-for="(data, pinyin_prefix) in regions" :key="pinyin_prefix">
				<view class="pinyin_prefix padding-left-sm padding-top-sm padding-bottom-sm text-sm text-bold">
					{{ pinyin_prefix }}</view>
				<view class="grid text-center">
					<view class="regions-item" v-for="item in data" :key="item.id" @tap="selected(item)">{{ item.title }}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
let map;
export default {
	data() {
		return {
			shopLocation:false,
			locationLoading: 'loading',
			location: {},
			regions: [],
			event: ''
		}
	},
	onLoad(options) {
		if (options.event) {
			this.event = options.event;
		}
		const storage = this.$utils.useStorage();
		const city = storage.get('city');
		if (city) {
			this.regions = city;
		}
        map = this.$utils.useMap(()=>{
			this.shopLocation=true;
			if(city){
				this.getLocation();
			}
		});
		this.$utils.$api.Regions.getRegions().then(data => {
			this.regions = this.serializeData(data);
			if(!city){
				this.getLocation();
			}
			storage.set('city', this.regions);
		}).catch(err => {
            this.$utils.$message.error(err.msg);
        });
	},
	methods: {
		getLocation() {
            if(!map.isReady()){return;}
			this.locationLoading = 'loading';
            map.getCurrentPosition().then((result) => {
				map.getAddress([result.position.lng, result.position.lat]).then(result=>{
					this.locationLoading = 'success';
					const city = result.regeocode.addressComponent.city;
					for (const pinyin_prefix in this.regions) {
						if (Object.hasOwnProperty.call(this.regions, pinyin_prefix)) {
							const cityData = this.regions[pinyin_prefix];
							for (let i = 0; i < cityData.length; i++) {
								const item = cityData[i];
								if(item.title.includes(city)){
									this.location=item;
									return;
								}
							}
						}
					}
				}).catch(err=>{
					this.locationLoading = 'fail';
					console.log(err);
				})
            }).catch(() => {
				this.locationLoading = 'fail';
            });
		},
		serializeData(data) {
			let d = {};
			for (let i = 0; i < data.length; i++) {
				const province = data[i];
				if (province.children) {
					if (province.children.length > 1 || data.length > 1) {
						for (let j = 0; j < province.children.length; j++) {
							const city = province.children[j];
							if (!d[city.pinyin_prefix]) {
								d[city.pinyin_prefix] = [];
							}
							d[city.pinyin_prefix].push({
								id: city.id,
								title: city.title,
								level: city.level
							});
						}
					} else if (data.length === 1) {
						return this.serializeData(province.children);
					}
				}
			}
			return d;
		},
		selected(e) {
			if (this.event) {
				uni.$emit(this.event, e);
						this.$utils.$page.back();
			}
		}

	}
}
</script>

<style lang="scss" scoped>
.page {
	min-height: 100vh;
}

.pinyin_prefix {
	// 大写
	text-transform: uppercase;
}

.grid {
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 10px;
	padding: 20px;
}

.regions-item {
	grid-column: span 1;
	background-color: #FFFFFF;
	border-radius: 5px;
	padding: 5px;
	font-size: 24rpx;
	font-weight: 600;
	display: flex;
	justify-content: center;
	align-items: center;
}

.regions-item-2 {
	grid-column: span 2;
}
</style>
